//
//  TileWallView.m
//  etionUI
//
//  Created by wangjian on 7/17/13.
//
//

#import "TileWallView.h"
#import "XUIRefreshHeaderView.h"

#define DEF_TILES_MARGIN 12

@interface CTileWallView()<XUIRefreshHeaderViewDelegate>

@property (nonatomic, retain) UIScrollView *scrollWallView;
@property (nonatomic, retain) NSMutableArray *tileCells;
@property (nonatomic, assign) NSUInteger numberOfTilesInOneRow;
@property (nonatomic, assign) XUIRefreshHeaderView *refreshHeaderView;

@end

@implementation CTileWallView

@synthesize delegate = _delegate;
@synthesize tileSize = _tileSize;
@synthesize scrollWallView = _scrollWallView;
@synthesize tileCells = _tileCells;
@synthesize numberOfTilesInOneRow = _numberOfTilesInOneRow;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor colorWithHex:0xeff0f3 alpha:1.0];
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        scrollView.backgroundColor = [UIColor clearColor];
        scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        scrollView.delegate = self;
        scrollView.alwaysBounceVertical = YES;
        [self addSubview:scrollView];
        self.scrollWallView = scrollView;
        [scrollView release];
        
        self.tileCells = [NSMutableArray array];

        self.tileSize = CGSizeMake((frame.size.width-3*DEF_TILES_MARGIN)/2, (frame.size.width-3*DEF_TILES_MARGIN)/2);
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureResponse:)];
        tapGesture.numberOfTapsRequired = 1;
        tapGesture.numberOfTouchesRequired = 1;
        [self.scrollWallView addGestureRecognizer:tapGesture];
        [tapGesture release];
    }
    return self;
}

- (void)setAlwaysBounceVertical:(BOOL)alwaysBounceVertical
{
    self.scrollWallView.alwaysBounceVertical = alwaysBounceVertical;
}

- (void)setShowRefreshHeader:(BOOL)showRefreshHeader
{
    _showRefreshHeader = showRefreshHeader;
    if (showRefreshHeader == NO)
    {
        [_refreshHeaderView removeFromSuperview];
        _refreshHeaderView = nil;
    }
    else
    {
        if (_refreshHeaderView == nil)
        {
            _refreshHeaderView = [[[XUIRefreshHeaderView alloc] initWithDelegate:self] autorelease];
//            _refreshHeaderView.refreshingView=[[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"refresh_head.png"]]autorelease];
//            _refreshHeaderView.hiddenTitle=YES;
//            _refreshHeaderView.presentType=XUIRefreshHeaderViewPresentTypePinToTop;
//            _refreshHeaderView.refreshIndicatorAnimatedType=XUIRefreshIndicatorAnimatedTypeFollowScroll;
//            _refreshHeaderView.refreshingAnimatedType=XUIRefreshingAnimatedTypeImageRotate;
//            _refreshHeaderView.stateTextAlignment=NSTextAlignmentLeft;
            [self.scrollWallView addSubview:_refreshHeaderView];
            if(_refreshHeaderView.hiddenTitle==NO)
            {
                id date=[self refreshHeaderViewLastUpdateTime:_refreshHeaderView];
                [_refreshHeaderView setLastUpdateTime:date];
            }
        }
    }
}

- (void)dealloc
{
    [_scrollWallView release];
    [_tileCells release];
    [super dealloc];
}

- (CTileWallCellView *)tileCellAtIndex:(NSUInteger)index
{
    if (index < self.tileCells.count)
    {
        return [self.tileCells objectAtIndex:index];
    }
    CTileWallCellView *cell = [[[CTileWallCellView alloc]
                               initWithFrame:CGRectMake(DEF_TILES_MARGIN + (index % self.numberOfTilesInOneRow) * (self.tileSize.width + DEF_TILES_MARGIN),
                                                        DEF_TILES_MARGIN + (index / self.numberOfTilesInOneRow) * (self.tileSize.height + DEF_TILES_MARGIN),
                                                        self.tileSize.width,
                                                        self.tileSize.height)] autorelease];
    return cell;
}

- (CTileView *)tileViewAtIndex:(NSInteger)index
{
    if (index < self.tileCells.count)
    {
        CTileWallCellView *cell = [self.tileCells objectAtIndex:index];
        return cell.tileView;
    }
    return nil;
}

- (void)reloadData
{
    if (self.delegate == nil)
    {
        return;
    }
    
    NSUInteger oldTilesNum = [self.tileCells count];
    NSUInteger newTilesNum = [self.delegate numberOfTilesInTileWallView:self];
    
    //init base info
    if ([self.delegate respondsToSelector:@selector(sizeOfTileInTileWallView:)])
    {
        self.tileSize = [self.delegate sizeOfTileInTileWallView:self];
    }
    self.numberOfTilesInOneRow = (self.width - DEF_TILES_MARGIN) / (self.tileSize.width + DEF_TILES_MARGIN);
    [self.scrollWallView scrollRectToVisible:CGRectMake(0, 0, self.scrollWallView.width, 10) animated:YES];
    
    //add cell view
    if (oldTilesNum < newTilesNum)
    {
        for (NSUInteger i=oldTilesNum; i<newTilesNum; i++)
        {
            [self.tileCells addObject:[self tileCellAtIndex:i]];
            [self.scrollWallView addSubview:[self.tileCells objectAtIndex:i]];
        }
        self.scrollWallView.contentSize = CGSizeMake(self.width, (newTilesNum + self.numberOfTilesInOneRow - 1) / self.numberOfTilesInOneRow * (self.tileSize.height + DEF_TILES_MARGIN) + DEF_TILES_MARGIN);
    }
    
    //update cell view animated
    srandom(ToUInt time(NULL));
    for (NSUInteger i=0; i<self.tileCells.count; i++)
    {
        NSUInteger randomNumber = random() % 30;
        NSTimeInterval delayTime = randomNumber / 100.0;
        CTileWallCellView *tileCell = [self.tileCells objectAtIndex:i];
        CTileView *tileView = nil;
        if (i < newTilesNum)
        {
            tileView = [self.delegate tileWallView:self tileAtIndex:i];
        }
        [tileCell relpeceTileView:tileView afterDelay:delayTime complete:^(BOOL isFinished) {
            if (i >= newTilesNum)
            {
                [tileCell removeFromSuperview];
                [self.tileCells removeObject:tileCell];
                if (self.tileCells.count == newTilesNum)
                {
                    self.scrollWallView.contentSize = CGSizeMake(self.width, (newTilesNum + self.numberOfTilesInOneRow - 1) / self.numberOfTilesInOneRow * (self.tileSize.height + DEF_TILES_MARGIN) + DEF_TILES_MARGIN);
                }
            }
        }];
    }
}

- (void)tapGestureResponse:(UITapGestureRecognizer *)tapgesture
{
    CGPoint point = [tapgesture locationInView:self.scrollWallView];
    if ((NSInteger)point.y % (NSInteger)(self.tileSize.height+DEF_TILES_MARGIN) < DEF_TILES_MARGIN
     || (NSInteger)point.x % (NSInteger)(self.tileSize.width+DEF_TILES_MARGIN) < DEF_TILES_MARGIN)
    {
        return;
    }
    else
    {
        NSInteger row = point.y / (self.tileSize.height+DEF_TILES_MARGIN);
        NSInteger col = point.x / (self.tileSize.width+DEF_TILES_MARGIN);
        NSInteger index = row * self.numberOfTilesInOneRow + col;
        if (index >= [self.delegate numberOfTilesInTileWallView:self])
        {
            return;
        }
        if ([self.delegate respondsToSelector:@selector(tileWallView:didSelectedTileAtIndex:)])
        {
            [self.delegate tileWallView:self didSelectedTileAtIndex:index];
        }
    }
}

- (void)refreshHeaderViewBeginRefreshing:(XUIRefreshHeaderView *)view
{
    if ([self.delegate respondsToSelector:@selector(tileWallViewStartRefreshing:)])
    {
        [self.delegate tileWallViewStartRefreshing:self];
    }
}

-(id)refreshHeaderViewLastUpdateTime:(XUIRefreshHeaderView*)view
{
    if ([self.delegate respondsToSelector:@selector(titleWallViewRefreshHeaderViewLastUpdateTime:)])
    {
        return [self.delegate titleWallViewRefreshHeaderViewLastUpdateTime:self];
    }
    return nil;
}

- (void)endRefreshing
{
    [self.refreshHeaderView endRefreshing];
}

@end

